package com.uenpay.oem.ui.main.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qyx.android.message.type.PacketType;
import com.socks.library.KLog;
import com.uenpay.im.IMApplication;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.ui.contacts.ContactsActivity;
import com.uenpay.im.ui.old.activity.dynamic.DynamicActivity;
import com.uenpay.im.utilities.ToastUtil;
import com.uenpay.oem.R;
import com.uenpay.oem.common.AppConstant;
import com.uenpay.oem.common.RxBusEventConstant;
import com.uenpay.oem.data.bean.UserAuthInfo;
import com.uenpay.oem.receiver.Myreceiver;
import com.uenpay.oem.ui.auth.AuthActivity;
import com.uenpay.oem.ui.main.LucencyActivity;
import com.uenpay.oem.ui.trans.paycode.PayCodeActivity;
import com.uenpay.oem.ui.trans.receivable.QRCodeCollectionActivity;
import com.uenpay.oem.widget.PayCodeProvider;
import com.uenpay.util.app.base.BaseFragment;
import com.uenpay.util.imageloader.ImageLoader;
import com.uenpay.util.imageloader.ImageLoaderUtil;
import com.uenpay.util.rx.CommonEvent;
import com.uenpay.util.rx.RxBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observable;
import rx.functions.Action1;

/**
 * Author: liulou Date: 2017/6/12. desc:
 */

public class HomeNewFragment extends BaseFragment implements HomeNewContact.View {

	public static final String TAG = "HomeNewFragment";

	@BindView(R.id.toolbar)
	Toolbar toolbar;
	@BindView(R.id.collapsing_toolbar)
	CollapsingToolbarLayout collapsingToolbar;
	@BindView(R.id.appbar)
	AppBarLayout appBarLayout;
	@BindView(R.id.viewpager)
	ViewPager vpHeader;
	@BindView(R.id.iv_avatar)
	ImageView ivAvatar;
	@BindView(R.id.ll_charge)
	LinearLayout llCharge;
	@BindView(R.id.main_content)
	CoordinatorLayout mainContent;
	@BindView(R.id.rl_friend_circle)
	RelativeLayout rlFriendCircle;

	private View llBannerDate;
	private View llBannerAmount;
	private List<View> banners = new ArrayList<>();
	private UserAuthInfo mUserAuthInfo = null;
	private Unbinder mUnbinder;
	private HomeNewContact.Presenter MHomeNewpresenter;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setHasOptionsMenu(true);
	}

	@Override
	protected void onCreateView(Bundle savedInstanceState) {
		super.onCreateView(savedInstanceState);
		setContentView(R.layout.fragment_home_new_layout);
		mUnbinder = ButterKnife.bind(this, getContentView());

		initView();
		initToolbar();
		initData();
	}

	private void initData() {

		TextView tvweek = (TextView) llBannerDate.findViewById(R.id.tv_week);
		TextView tvyear = (TextView) llBannerDate.findViewById(R.id.tv_year);
		TextView tvday = (TextView) llBannerDate.findViewById(R.id.tv_day);
		long time = System.currentTimeMillis();
		Date date = new Date(time);
		SimpleDateFormat format = new SimpleDateFormat("dd");
		tvday.setText("" + format.format(date));

		format = new SimpleDateFormat("MM/yyyy");
		tvyear.setText("" + format.format(date));

		format = new SimpleDateFormat("EEEE");
		tvweek.setText("" + format.format(date));

	}



	public void initToolbar() {

		toolbar.inflateMenu(R.menu.menu_home);
		MenuItem payCodeMenu = toolbar.getMenu().findItem(R.id.menu_paycode);
		final PayCodeProvider payCodeProvider = (PayCodeProvider) MenuItemCompat.getActionProvider(payCodeMenu);
		MenuItem contactsMenu = toolbar.getMenu().findItem(R.id.menu_contacts);
		final ImageView ivContacts = (ImageView) contactsMenu.getActionView().findViewById(R.id.iv_contacts);
		MenuItem notifyMenu = toolbar.getMenu().findItem(R.id.menu_notification);
		final ImageView ivNotify = (ImageView) notifyMenu.getActionView().findViewById(R.id.iv_notify);
		appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
			@Override
			public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

				KLog.d(TAG, "onOffsetChanged: verticalOffset--->" + verticalOffset + " applayout height--->" + appBarLayout.getHeight());
				if ((float) verticalOffset / appBarLayout.getHeight() < -0.6) {
					payCodeProvider.getTitleView().setTextColor(getResources().getColor(R.color.black));
					payCodeProvider.getIconView().setImageResource(R.drawable.ic_paycode_black);
					ivContacts.setImageResource(R.drawable.ic_contacts_black);
					ivNotify.setImageResource(R.drawable.ic_notify_readed_white);
				} else {
					payCodeProvider.getTitleView().setTextColor(getResources().getColor(R.color.white));
					payCodeProvider.getIconView().setImageResource(R.drawable.ic_paycode_white);
					ivContacts.setImageResource(R.drawable.ic_contacts_white);
					ivNotify.setImageResource(R.drawable.ic_notify_readed_white);
				}
			}
		});
		// 付款码
		payCodeProvider.setOnClickListener(new PayCodeProvider.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (mUserAuthInfo.getIsReal() == 0) {
					ToastUtil.showToast(getActivity(), "请先实名认证");
					return;
				}
				Intent payCode = new Intent(getActivity(), PayCodeActivity.class);
				startActivity(payCode);
			}
		});
		// 联系人
		ivContacts.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getActivity().startActivity(new Intent(getActivity(), ContactsActivity.class));
			}
		});
		// 消息

		ivNotify.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ToastUtil.showToast(getApplicationContext(), "暂未开放");
			}
		});
	}

	private void initView() {
		setPresenter(null);
		MHomeNewpresenter.getBalance();
		MHomeNewpresenter.getUserInfo();

		final String url = APIConfiguration.getAvatarUrlNormal(IMApplication.getCustId(), PacketType.PERSONAL);
		ImageLoaderUtil.getInstance().loadImage(getActivity(), new ImageLoader.Builder().imgView(ivAvatar).roundRadius(3).url(url).build());
		llBannerDate = LayoutInflater.from(getActivity()).inflate(R.layout.view_home_banner_date, null);
		llBannerAmount = LayoutInflater.from(getActivity()).inflate(R.layout.view_home_banner_amount, null);
		banners.add(llBannerAmount);
		banners.add(llBannerDate);
		vpHeader.setAdapter(new PagerAdapter() {
			@Override
			public int getCount() {
				return banners.size();
			}

			@Override
			public boolean isViewFromObject(View view, Object object) {
				return view == object;
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				container.addView(banners.get(position));
				return banners.get(position);
			}

			@Override
			public void destroyItem(ViewGroup container, int position, Object object) {
				container.removeView(banners.get(position));
			}
		});
		vpHeader.setCurrentItem(1);
		Observable<CommonEvent> observable = RxBus.$().register(TAG);
		RxBus.$().OnEvent(observable, new Action1<Object>() {
			@Override
			public void call(Object o) {
				CommonEvent event = (CommonEvent) o;
				switch (event.getWhat()) {
				case RxBusEventConstant.EVENT_AVATAR_CHANGE:
					ImageLoaderUtil.getInstance().loadImage(getActivity(),
							new ImageLoader.Builder().isCache(false).imgView(ivAvatar).roundRadius(3).url(url).build());
					break;
					case RxBusEventConstant.EVENT_RECHARGE_SUCCESS:
						MHomeNewpresenter.getBalance();
						break;


				}

			}
		});


	}

	@OnClick(R.id.ll_charge)
	public void chargrClick() {
		Intent it = new Intent(getActivity(), AuthActivity.class);
		startActivity(it);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnbinder.unbind();
		RxBus.$().unregister(TAG);

	}

	// 朋友圈
	@OnClick(R.id.rl_friend_circle)
	public void onClick() {
		getActivity().startActivity(new Intent(getActivity(), DynamicActivity.class));

	}

	@Override
	public void onResume() {
		super.onResume();
		MHomeNewpresenter.getBalance();
	}

	@Override
	public void showBalance(String balance) {
		TextView textView = (TextView) llBannerAmount.findViewById(R.id.tv_property);
		textView.setText(balance);
	}

	@Override
	public void showUserInfo(UserAuthInfo info) {
		mUserAuthInfo=info;
		if (info.getIsReal() == 0) {
			startActivity(new Intent(getActivity(), LucencyActivity.class));
		}

	}

	@Override
	public void showLoading() {

	}

	@Override
	public void dismissLoading() {

	}

	@Override
	public void setPresenter(Object presenter) {
		MHomeNewpresenter = new HomeNewPresenter(this);
	}

	@Override
	public void showToast(String msg) {

	}
}
